<?php
namespace admin\action;

use herosphp\bean\Beans;
use herosphp\exception\UnSupportedOperationException;
use herosphp\http\HttpRequest;
use herosphp\utils\AjaxResult;
use Workerman\Protocols\Http;

/**
 * operations action
 * @package system\action
 * @author yangjian<yangjian102621@gmail.com>
 */
class OperationsAction extends CommonAction {

    protected $serviceBean = 'system.operation.service';
    protected $actionTitle = '操作权限';

    //数据列表页面
    public function index( HttpRequest $request ) {

        $optkey = $request->getParameter('optkey', 'trim');
        $module = $request->getParameter('module', 'trim');

        $conditions = array();
        if ( $optkey ) $conditions['optkey'] = "%{$optkey}%";
        if ( $module ) $conditions['module'] = $module;
        $this->setConditions($conditions);

        parent::index($request);
        $this->setView('system/operations_index');
        $this->assign('breadcrumb', array('系统管理', '权限管理'));
    }

    //数据添加页面
    public function add(HttpRequest $request) {
        throw new UnSupportedOperationException("暂时不支持此操作");
    }

    //数据编辑页面
    public function edit(HttpRequest $request) {
        $id = $request->getParameter('id', 'intval');
        if ( $id <= 0 ) {
            AjaxResult::ajaxResult(AjaxResult::OP_FAILURE, self::NO_RECORDS);
        }
        $service = Beans::get($this->getServiceBean());
        $item = $service->getItem($id);
        if ( empty($item) ) {
            AjaxResult::ajaxResult(AjaxResult::OP_FAILURE, self::NO_RECORDS);
        }
        AjaxResult::ajaxResult(AjaxResult::OP_SUCCESS, null, $item);
    }

    //插入数据操作
    public function insert(HttpRequest $request) {

        $data = $request->getParameter('data');
        $service = Beans::get($this->getServiceBean());
        parent::__insert($data, function() use ($service) {
            $service->flush();
        });
    }

    //更新数据操作
    public function update(HttpRequest $request) {

        $data = $request->getParameter('data');
        $id = $request->getParameter('id', 'trim');
        $service = Beans::get($this->getServiceBean());
        parent::__update($data, $id, function() use ($service) {
            $service->flush();
        });
    }

    //批量保存
    public function quicksave(HttpRequest $request) {
        $service = Beans::get($this->getServiceBean());
        parent::quicksave($request, function() use ($service) {
            $service->flush();
        });
    }

    //删除数据
    public function delete(HttpRequest $request) {
        parent::delete($request, function() {
            $service = Beans::get($this->getServiceBean());
            $service->flush();
        });
    }
}
